<script setup lang="ts">
import AccountHeader from "./AccountHeader.vue";
import { useAccountTable } from "./index";
import { useAccountAggregationStore } from "@/store/modules/accountAggregationStore";
import { storeToRefs } from "pinia";
import { computed, onMounted } from "vue";
import ExpandTabs from "./ExpandTabs.vue";

defineOptions({
  name: "account-index"
});
// Store setup
const accountAggregationStore = useAccountAggregationStore();
const { isLoading, lastUpdateTime, aggregation } = storeToRefs(
  accountAggregationStore
);
const { refreshAggregation } = accountAggregationStore;

const {
  accountSearch,
  symbolSearch,
  getRowKey,
  expandRowKeys,
  expandAll,
  collapseAll,
  unpackAggregation,
  onExpandChange,
  filterTableData,
  calculateTotals,
  accountColumns,
  tableSize
} = useAccountTable();

// Lifecycle hooks
onMounted(async () => {
  await accountAggregationStore.init();
});

const filteredTableData = computed(() => {
  return filterTableData(unpackAggregation(aggregation.value));
});

const totals = computed(() => {
  return calculateTotals(filteredTableData.value);
});
</script>

<template>
  <div>
    <AccountHeader
      v-model:account-search="accountSearch"
      v-model:symbol-search="symbolSearch"
      :total-balance="totals.totalBalance"
      :total-pnl="totals.totalPnl"
      :is-loading="isLoading"
      :last-update-time="lastUpdateTime"
      @expand-all="() => expandAll(filteredTableData)"
      @collapse-all="collapseAll"
      @refresh="refreshAggregation"
    />

    <pure-table
      class="my-1 sm:my-2 md:my-3"
      :size="tableSize"
      :columns="accountColumns"
      :data="filteredTableData"
      :row-key="getRowKey"
      :expand-row-keys="expandRowKeys"
      :row-class-name="
        ({ row }) =>
          expandRowKeys.includes(getRowKey(row)) ? 'bg-blue-100!' : ''
      "
      :default-sort="{ prop: 'account.balance', order: 'descending' }"
      border
      @expand-change="onExpandChange"
    >
      <template #expand="{ row }">
        <ExpandTabs :row="row" />
      </template>
    </pure-table>
  </div>
</template>
